package com.eastcom.collection.process;

import com.eastcom.collection.distributor.DPService
import com.eastcom.collection.provider.*
import com.eastcom.collection.tools.file.FileUtils
import com.eastcom.collection.context.*
import javax.annotation.Resource
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import org.springframework.stereotype.Component


@Component("serverInitProcess")
public class ServerInitProcess {
	private static Log logger = LogFactory.getLog(ServerInitProcess.class);
	@Resource(name = "threadPool")
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;
	public void init(){
		try {
			DynamicBeanRegisterProvider beanRegister = SpringContextProvider.getBean("beanRegister")
			beanRegister.setApplicationContext(SpringContextProvider.getApplicationContext())
			DynamicBeanDomianProvider.init()
			String serverInitShell = ServerContext.rootPath+"/config/base/server_shell.groovy"
			if(serverInitShell != null){
				File f = new File(serverInitShell)
				if(f.isFile()){
					Binding binding = new Binding()
					binding.setVariable("flag","startDerbyDataBase")
					GroovyShell shell = new GroovyShell(binding)
					Script script = shell.parse(new File(serverInitShell))
					script.run()
				}
			}
			String dpServiceFloag = PropertyPlaceholderConfigurerProvider.getContextProperty("DPSERVICE_FLAG")
			if(dpServiceFloag != null && dpServiceFloag.equalsIgnoreCase("TRUE")){
				threadPoolTaskExecutor.submit(new Runnable() {
							@Override
							public void run() {
								DPService dPService = SpringContextProvider.getBean("dpService");
								dPService.startService()
							}
						});
			}
			FileUtils fileUtils = new FileUtils()
			String[] path
			String groovyScriptDir = PropertyPlaceholderConfigurerProvider.getContextProperty("GroovyDir")
			if(groovyScriptDir == null || groovyScriptDir.equals("")){
				path = new String[1]
				path[0] = "config"
			}else{
				path = groovyScriptDir.split("\\s*,\\s*")
			}
			path.each {
				List<File> files = fileUtils.listDirAndSubDirFiles(ServerContext.rootPath+"/"+it, ".groovy")
				if(files != null){
					files.each {
						ServerContext.scriptFilePath.add(it.getAbsolutePath())
					}
				}
			}
			TaskInitProcess taskInitProcess = SpringContextProvider.getBean("taskInitProcess");
			taskInitProcess.init(ServerContext.scriptFilePath);
		} catch (Exception e) {
			e.printStackTrace()
		}
	}
}
